import { ref, Ref, onUnmounted, onMounted } from 'vue';
import * as echarts from 'echarts/core';

import { useProjectStore } from '@/store';

const getRotate = () => {
  // 获取元素的计算样式
  let element: any = document.getElementById('app'); //需要全屏容器的id
  // const style = window.getComputedStyle(element);
  // 获取transform属性的值
  const transformValue = element.style.transform; //style.getPropertyValue('transform') || 'none';
  // console.log(transformValue,'获取当前旋转属性')
  // 检查transform值是否包含rotate(90deg)
  // 注意：这只是一个简单的检查，它不会处理多个变换或不同的单位（如rad）
  // 也不会处理3D变换或矩阵变换
  const hasRotate90 = transformValue.includes('rotate(90deg)');

  return hasRotate90;
};
const isMobile = navigator.userAgent.match(
  /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i,
);
export const isAndroid = () => {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;

  // Windows Phone must come first because its UA also contains "Android"
  if (/windows phone/i.test(userAgent)) {
    return false; // 不是安卓，是Windows Phone
  }

  // Android
  if (/android/i.test(userAgent)) {
    return true;
  }

  // iOS
  if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
    return false; // 不是安卓，是iOS
  }

  return false; // 不是安卓，可能是其他设备或浏览器
};
const store = useProjectStore();
/**
 * eChart hook
 * @param domId
 * @param chart
 */

let startX = ref(0);
let isDragging = ref(false);
let scrollXOnMouseDown = ref(0);
let timers = ref();
let startY = ref(0);
const isScrolling = ref(false);
const timer = ref();
export const openExhibitModeShow = (e: number, moduleId: number, lock: boolean) => {
  //打开展品弹框方法
  if (lock) {
    store.exhibitsShowpieceid = e;
    store.exhibitsModuleId = moduleId;
    store.exhibitsInfoShow = true;
  }
};
const isDingTalkBrowser = () => {
  var ua = navigator.userAgent.toLowerCase();
  // 检查用户代理字符串是否包含"dingtalk"
  return ua.indexOf('dingtalk') > -1;
};
export const mouseMove = (id: string) => {
  const scrollContainer = document.getElementById(id);

  scrollContainer.addEventListener('mousedown', (e) => {
    if (e.button === 0) {
      isDragging.value = true;
    }

    startX.value = e.clientX;
    scrollXOnMouseDown.value = scrollContainer.scrollLeft;
  });
  if (!isMobile) {
    scrollContainer.addEventListener('mousemove', (e) => {
      // console.log()
      const store = useProjectStore();
      if (!isDragging.value) return;

      scrollXOnMouseDown.value = scrollContainer.scrollLeft;
      const deltaX = e.clientX - startX.value;
      scrollContainer.scrollLeft -= deltaX;
      if (e.clientX < startX.value + 10 && e.clientX < startX.value) {
        scrollContainer.scrollLeft += 10;
      } else if (e.clientX > startX.value + 10 && e.clientX > startX.value) {
        scrollContainer.scrollLeft -= 10;
      }
      startX.value = e.clientX;
    });
  }
  let isRotate = getRotate();
  let isAndroidS = isAndroid();
  let ddType = isDingTalkBrowser();
  if (isMobile) {
    document.addEventListener('touchstart', function (e) {
      if (isRotate && isAndroidS) {
        startY.value = e.touches[0].clientY;
        isScrolling.value = false; // 重置状态
        e.preventDefault();
      }
    });

    // 监听触摸移动事件
    document.addEventListener('touchmove', function (e) {
      if (store.exhibitsInfoShow && store.childRemarksShow) {
        e.stopPropagation();
        e.preventDefault();
        return;
      }
      if (ddType && isAndroidS) {
        // 获取当前触摸点的Y坐标
        // console.log('触发', window.orientation);
        let currentY = e.touches[0].clientY;

        // 计算Y轴上的移动距离
        let scrollDistance = currentY - startY.value;
        if (store.exhibitsInfoShow) {
          return;
        } 
        // 判断滑动方向 
        console.log(scrollDistance);
        if (scrollDistance > 0) {
          // 向下滑动
          if (!isScrolling.value) {
            // scrollContainer.scrollLeft -= 10;
          }
        } else if (scrollDistance < 0) {
          // 向上滑动

          if (!isScrolling.value) {
            console.log('向下滑动');
            // scrollContainer.scrollLeft += 10;
          }
        }
        const deltaX = e.touches[0].clientX - startX.value;
        scrollContainer.scrollLeft -= deltaX;
        if (e.touches[0].clientX < startX.value) {
          scrollContainer.scrollLeft += 10;
        } else if (e.touches[0].clientX > startX.value) {
          scrollContainer.scrollLeft -= 10;
        }
        startX.value = e.touches[0].clientX;
      }
    });
    document.addEventListener('touchend', function (e) {
      isScrolling.value = true; // 重置状态
    });
    // document.addEventListener('touchstart', function (e) {
    //   // if (isRotate) {
    //   //   startY.value = e.touches[0].clientY;
    //   //   startX.value = e.touches[0].clientX;
    //   //   isScrolling.value = false; // 重置状态
    //   //   // e.stopPropagation();
    //   // }
    // });

    // // 监听触摸移动事件;
    // document.addEventListener('touchmove', function (e) {
    //   // 获取当前触摸点的Y坐标

    //   if (store.exhibitsInfoShow && store.childRemarksShow) {
    //     e.stopPropagation();
    //     return;
    //   }
    //   // 判断滑动方向
    // });
    // document.addEventListener('touchend', function (e) {
    //   isScrolling.value = true; // 重置状态
    // });
  }

  document.addEventListener('mouseup', (e) => {
    // if(isDragging.value){

    // console.log(deltaX)
    // }

    isDragging.value = false;
  });

  document.addEventListener('mouseleave', () => {
    isDragging.value = false;
  });
};
export const useChart = (domId: string): Ref<echarts.ECharts> => {
  let chartContainer: HTMLCanvasElement;
  const selfChart = ref<echarts.ECharts | any>();
  const updateContainer = () => {
    // TODO resize 报错，响应式的问题，待处理
    selfChart.value.resize({
      width: chartContainer.clientWidth,
      height: chartContainer.clientHeight,
    });
  };

  onMounted(() => {
    if (!chartContainer) {
      chartContainer = document.getElementById(domId) as HTMLCanvasElement;
    }
    selfChart.value = echarts.init(chartContainer);
  });

  window.addEventListener('resize', updateContainer, false);

  onUnmounted(() => {
    window.removeEventListener('resize', updateContainer);
  });

  return selfChart;
};

/**
 * counter utils
 * @param duration
 * @returns
 */
export const useCounter = (duration = 60): [Ref<number>, () => void] => {
  let intervalTimer;
  onUnmounted(() => {
    clearInterval(intervalTimer);
  });
  const countDown = ref(0);

  return [
    countDown,
    () => {
      countDown.value = duration;
      intervalTimer = setInterval(() => {
        if (countDown.value > 0) {
          countDown.value -= 1;
        } else {
          clearInterval(intervalTimer);
          countDown.value = 0;
        }
      }, 1000);
    },
  ];
};
